package com.mjf.io.output;

import org.junit.Test;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * FileOutputStream:字节输出流
 */
public class FileOutputStreamUse {

    /**
     * 将数据写入到文件中，如果文件不存在则创建文件
     * new FileOutputStream(outputFile) 创建文件输出流时会覆盖文件
     */
    @Test
    public void writeFile01() {
        String outputFile = "D:\\coding\\idea\\java-stu\\output\\hello.txt";
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(outputFile);
            // 写入一个字节
//            fos.write('H');
            // 写入字符串
            fos.write("hello,world".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * new FileOutputStream(outputFile, true) 追加文件
     */
    @Test
    public void writeFile02() {
        String outputFile = "D:\\coding\\idea\\java-stu\\output\\hello.txt";
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(outputFile, true);
            fos.write('\n');
            fos.write("hello,world".getBytes(), 0, 5);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
